<template>
  <BasicDrawer
      v-bind="$attrs"
      :showFooter="true"
      :okAuth="'unitmanage:unitEnterpriseDominant:edit'"
      @register="registerDrawer"
      @ok="handleSubmit"
      width="60%"
      destroyOnClose={true}
  >
      <template #title>
          <Icon :icon="getTitle.icon" class="m-1 pr-1" />
          <span> {{ getTitle.value }} </span>
      </template>
      <template #footer>
        <Button  @click="closeDrawer">  <Icon icon="i-ant-design:close-outlined" />取消</Button>
        <Button v-if="record.isNewRecord"  @click="handleBuildEdit" >  <Icon icon="i-ant-design:bank-outlined" />下一步</Button>
        <Button type="primary" @click="handleSubmit"> <Icon icon="i-ant-design:check-outlined" />确认</Button>
      </template>
      <BasicForm @register="registerForm" />
      <BaiduMap
          :path="BaiduMapPath"
          :bound="bound"
          @overlaycomplete="handleOverlayComplete"
          @clearPath="handleClearPath"
          @mapClick="handleMapClick"
          @addressReceived="handleAddressReceived"
      />
  </BasicDrawer>
  <template>
       <!-- 引入 unitBuilding/form.vue -->
       <ViewsUnitmanageUnitBuildingForm @register="registerBuildDrawer"  />
  </template>
</template>

<script lang="ts" setup>
import { ref, unref, computed, defineEmits, defineProps, watch } from 'vue';
import { useI18n } from '/@/hooks/web/useI18n';
import { useMessage } from '/@/hooks/web/useMessage';
import { router } from '/@/router';
import { Icon } from '/@/components/Icon';
import { BasicForm, FormSchema, useForm } from '/@/components/Form';
import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
import {
  UnitEnterpriseDominant,
  unitEnterpriseDominantListData,
  unitEnterpriseDominantSave,
  unitEnterpriseDominantForm
} from '/@/api/unitmanage/unitEnterpriseDominant';

import { areaTreeData } from '/@/api/sys/area';
import { Office, officeTreeData, officeListData } from '/@/api/sys/office';
import { dictDataListData } from '/@/api/sys/dictData';
import ViewsUnitmanageUnitBuildingForm from '/@/views/unitmanage/unitBuilding/form.vue';
import BaiduMap from '/@/components/BMap';
import { Modal, Button } from 'ant-design-vue';
import { useDrawer } from '/@/components/Drawer';

const emit = defineEmits(['success', 'register']);
const { t } = useI18n('unitmanage.unitEnterpriseDominant');
const { showMessage } = useMessage();
const { meta } = unref(router.currentRoute);
const record = ref<UnitEnterpriseDominant>({} as UnitEnterpriseDominant);
const ctrlPermi = ref<string>('');
const ctrlPermi1 = ref<string>('');
const op = ref<string>('');
const path = ref<any>([]);
const bound = ref<any>([]);
const Adress= ref<string>('');
const showContractDialog = ref(false);
const BaiduMapPath = ref<any>([]);
const BaiduMapBound = ref<any>([]);

const EnterpriseParams = ref<Recordable>({
  name: ''
});
const pliceParams = ref<Recordable>({
  name: '',
  dominantType: 'police_station'
});
const firePathParams = ref<Recordable>({
  name: '',
  dominantType: 'fire_management_unit'
});
const maintenanceParams = ref<Recordable>({
  name: '',
  dominantType: 'maintenance'
});
const ShowMessage=ref('')
const EnterpriseType= ref<string>('');
const DominantType= ref<string>('');
EnterpriseType.value =EnterpriseType.value? EnterpriseType.value : DominantType.value;
const getTitle = computed(() => ({
  icon: meta.icon || 'i-ant-design:book-outlined',
  value: record.value.isNewRecord ? t('编辑') : t('新增')
}));

const inputFormSchemas: FormSchema[] = [
    {
      label: t('主体类型'),
      field: 'dominantType',
      component: 'Select',
      componentProps: {
          maxlength: 100,
          dictType: 'dominant_type',
          fieldNames: {
              label: 'label',
              value: 'value'
          },
          allowClear: true,
          onSelect: (value: string) => {
            EnterpriseType.value = value;
            console.log(EnterpriseType.value);
          }
      },
      required: true
  },  
  {
      label: t('所属行政区划'),
      field: 'county',
      component: 'TreeSelect',
      ifShow: () => {return EnterpriseType.value === 'police_station' 
      || EnterpriseType.value === 'fire_management_unit'
      || EnterpriseType.value ==='maintenance'  
      || EnterpriseType.value === 'secure_enterprise'
      || EnterpriseType.value === 'detection'
      || EnterpriseType.value === ''
    },
      componentProps: {
          maxlength: 255,
          api: areaTreeData,
          allowClear: true,
          fieldNames: {
              label: 'name',
              value: 'id'
          }
      }
  },
  {
      label: t('所属主体'),
      field: 'unitCode',
      fieldLabel: 'name',
      component: 'TreeSelect',
      ifShow: () => {return EnterpriseType.value === 'police_station' 
      || EnterpriseType.value === 'fire_management_unit'
      || EnterpriseType.value ==='maintenance'
      || EnterpriseType.value === 'secure_enterprise'
      || EnterpriseType.value === 'detection'
      || EnterpriseType.value === ''
    },
      componentProps:{
        api:officeTreeData,
        fieldNames: { label: 'name', value: 'code' },
      },
      required: true
  },
  {
      label: t('直属消防管理单位'),
      field: 'firePathId',
      fieldLabel: 'firePath',
      component: 'Select',
      ifShow: () => {return EnterpriseType.value === 'police_station' 
      || EnterpriseType.value === 'fire_management_unit'
      || EnterpriseType.value === 'secure_enterprise'
      || EnterpriseType.value === 'detection'
      || EnterpriseType.value === ''
    },
      componentProps: () => {
          return {
              api: unitEnterpriseDominantListData,
              params: firePathParams.value,
              fieldNames: { label: 'name', value: 'unitCode' },
              resultField: 'list',
              notFoundContent: '未查询到记录',
              filterTreeNode: false,
              filterOption: false,
              allowClear: true,
              immediate: true,
              onSearch: (value: string) => {
                  firePathParams.value.name = value;
              }
          };
      },
  },
  {
      label: t('警务室'),
      field: 'policeId',
      fieldLabel: 'policeName',
      component: 'Select',
      ifShow: () => {return EnterpriseType.value === 'police_station' 
      || EnterpriseType.value === 'fire_management_unit'
      || EnterpriseType.value === 'secure_enterprise'
      || EnterpriseType.value === 'detection'
      || EnterpriseType.value === ''
    },
      componentProps: () => {
          return {
              api: unitEnterpriseDominantListData,
              params: pliceParams.value,
              fieldNames: { label: 'name', value: 'unitCode' },
              resultField: 'list',
              notFoundContent: '未查询到记录',
              filterTreeNode: false,
              allowClear: true,
              filterOption: false,
              immediate: true,
              onSearch: (value: string) => {
                  pliceParams.value.name = value;
              }
          };
      }
  },
  {
      label: t('维保企业'),
      field: 'maintenanceId',
      fieldLabel: 'maintenanceName',
      component: 'Select',
      ifShow: () => {return EnterpriseType.value === 'police_station' 
      || EnterpriseType.value === 'fire_management_unit'
      || EnterpriseType.value === 'secure_enterprise'
      || EnterpriseType.value === 'detection'
      || EnterpriseType.value === ''
    },
      componentProps: () => {
          return {
              api: unitEnterpriseDominantListData,
              params: maintenanceParams.value,
              fieldNames: { label: 'name', value: 'unitCode' },
              resultField: 'list',
              notFoundContent: '未查询到记录',
              filterTreeNode: false,
              filterOption: false,
              allowClear: true,
              immediate: true,
              onSearch: (value: string) => {
                  maintenanceParams.value.name = value;
              }
          };
      }
  },
  {
      label: t('主体建筑类型'),
      field: 'monomer',
      component: 'RadioGroup',
      ifShow: () => {return EnterpriseType.value === 'police_station' 
      || EnterpriseType.value === 'fire_management_unit'
      || EnterpriseType.value === 'secure_enterprise'
      || EnterpriseType.value === 'detection'
      || EnterpriseType.value === ''
    },
      componentProps: {
          options: [
              { label: '建筑局部', value: '1' },
              { label: '多栋建筑', value: '2' }
          ],
          maxlength: 100,
          allowClear: true
      }
  },
  {
      label: t('固定电话'),
      field: 'tel',
      component: 'Input',
      ifShow: () => {return EnterpriseType.value === 'police_station' 
      || EnterpriseType.value === 'fire_management_unit'
      || EnterpriseType.value ==='maintenance'
      || EnterpriseType.value === 'secure_enterprise'
      || EnterpriseType.value === 'detection'
      || EnterpriseType.value === ''
    },
      componentProps: {
          maxlength: 100,
          allowClear: true
      }
  },
  {
      label: t('管理员姓名'),
      field: 'contacts',
      component: 'Input',
      ifShow: () => {return EnterpriseType.value === 'police_station' 
      || EnterpriseType.value === 'fire_management_unit'
      || EnterpriseType.value ==='maintenance'
      || EnterpriseType.value === 'secure_enterprise'
      || EnterpriseType.value === 'detection'
      || EnterpriseType.value === ''
    },
      componentProps: {
          maxlength: 100,
          allowClear: true
      },
      required:true
  },
  {
      label: t('管理员电话'),
      field: 'mobile',
      component: 'Input',
      ifShow: () => {return EnterpriseType.value === 'police_station' 
      || EnterpriseType.value === 'fire_management_unit'
      || EnterpriseType.value ==='maintenance'
      || EnterpriseType.value === 'secure_enterprise'
      || EnterpriseType.value === 'detection'
      || EnterpriseType.value === ''
    },
      componentProps: {
          maxlength: 100,
          allowClear: true
      },
      required:true
  },
  {
      label: t('主体规模'),
      field: 'employeesNum',
      component: 'Input',
      ifShow: () => {return EnterpriseType.value === 'police_station' 
      || EnterpriseType.value === 'fire_management_unit'
      || EnterpriseType.value === 'secure_enterprise'
      || EnterpriseType.value === 'detection'
      || EnterpriseType.value === ''
    },
      componentProps: {
          maxlength: 100,
          allowClear: true
      }
  },
  {
      label: t('详细地址'),
      field: 'address',
      component: 'Input',
      ifShow: () => {return EnterpriseType.value === 'police_station' 
      || EnterpriseType.value === 'fire_management_unit'
      || EnterpriseType.value ==='maintenance'
      || EnterpriseType.value === 'secure_enterprise'
      || EnterpriseType.value === 'detection'
      || EnterpriseType.value === ''
    },
      componentProps: {
          maxlength: 100,
          allowClear: true,
      }
  },
  {
      label: t('联动消防力量'),
      field: 'unionEnterprise',
      fieldLabel: 'remarks',
      component: 'Select',
      ifShow: () => {return EnterpriseType.value === 'police_station' 
      || EnterpriseType.value === 'fire_management_unit'
      || EnterpriseType.value === 'secure_enterprise'
      || EnterpriseType.value === 'detection'
      || EnterpriseType.value === ''
    },
      componentProps: () => {
          return {
              api: unitEnterpriseDominantListData,
              params: EnterpriseParams.value,
              fieldNames: { label: 'name', value: 'unitCode' },
              resultField: 'list',
              notFoundContent: '未查询到记录',
              filterTreeNode: false,
              allowClear: true,
              filterOption: false,
              immediate: true,
              mode: 'multiple',
              onSearch: (value: string) => {
                  EnterpriseParams.value.name = value;
              }
          };
      },
  },
  {
      label: t('企业状态'),
      field: 'state',
    //   fieldLabel: 'status',
      component: 'Select',
      ifShow: () => {return EnterpriseType.value === 'police_station' 
      || EnterpriseType.value === 'fire_management_unit'
      || EnterpriseType.value === 'secure_enterprise'
      || EnterpriseType.value === 'detection'
      || EnterpriseType.value === ''
    },
      componentProps: {
          maxlength: 100,
          options: [
              { label: '正常监控', value: '正常监控' },
              { label: '维保', value: '维保' },
              { label: '监督检查', value: '监督检查' },
              { label: '检测', value: '检测' }
          ],
          allowClear: true
      }
  },
  {
      label: t('是否永久有效'),
      field: 'validForever',
    //   fieldLabel: 'validForever',
      component: 'RadioGroup',
      ifShow: () => {return EnterpriseType.value === 'police_station' 
      || EnterpriseType.value === 'fire_management_unit'
      || EnterpriseType.value === 'secure_enterprise'
      || EnterpriseType.value === 'detection'
      || EnterpriseType.value === ''
    },
      componentProps: {
          maxlength: 100,
          options: [
              { label: '是', value: "true" },
              { label: '否', value: "false"}
          ],
        //   allowClear: true
      }
  },
  {
      label: t('有效期'),
      field: 'expirationDate',
      component: 'DatePicker',
      ifShow: () => {return EnterpriseType.value === 'police_station' 
      || EnterpriseType.value === 'fire_management_unit'
      || EnterpriseType.value === 'secure_enterprise'
      || EnterpriseType.value === 'detection'
      || EnterpriseType.value === ''
    },
      componentProps: {
          maxlength: 100,
          allowClear: true
      }
  },
  {
      label: t('消防安全责任人'),
      field: 'responsiblePerson',
      component: 'Input',
      ifShow: () => {return EnterpriseType.value === 'police_station' 
      || EnterpriseType.value === 'fire_management_unit'
      || EnterpriseType.value === 'secure_enterprise'
      || EnterpriseType.value === 'detection'
      || EnterpriseType.value === ''
    },
      componentProps: {
          maxlength: 100,
          allowClear: true
      }
  },
  {
      label: t('消防安全责任人电话'),
      field: 'responsiblePersonPhone',
      component: 'Input',
      ifShow: () => {return EnterpriseType.value === 'police_station' 
      || EnterpriseType.value === 'fire_management_unit'
      || EnterpriseType.value === 'secure_enterprise'
      || EnterpriseType.value === 'detection'
      || EnterpriseType.value === ''
    },
      componentProps: {
          maxlength: 100,
          allowClear: true
      }
  },
  {
      label: t('消防安全管理员姓名'),
      field: 'securityAdmin',
      component: 'Input',
      ifShow: () => {return EnterpriseType.value === 'police_station' 
      || EnterpriseType.value === 'fire_management_unit'
      || EnterpriseType.value === 'secure_enterprise'
      || EnterpriseType.value === 'detection'
      || EnterpriseType.value === ''
    },
      componentProps: {
          maxlength: 100,
          allowClear: true
      }
  },
  {
      label: t('消防安全管理员电话'),
      field: 'securityAdminPhone',
      component: 'Input',
      ifShow: () => {return EnterpriseType.value === 'police_station' 
      || EnterpriseType.value === 'fire_management_unit'
      || EnterpriseType.value === 'secure_enterprise'
      || EnterpriseType.value === 'detection'
      || EnterpriseType.value === ''
    },
      componentProps: {
          maxlength: 100,
          allowClear: true
      }
  },
];

const [registerForm, { resetFields, setFieldsValue, validate,getFieldsValue }] = useForm({
  labelWidth: 120,
  schemas: inputFormSchemas,
  baseColProps: { md: 24, lg: 12 }
});

const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  setDrawerProps({ loading: true });
  await resetFields();
  const res = await unitEnterpriseDominantForm(data);
  BaiduMapPath.value = res.unitEnterpriseDominant.path ? JSON.parse(res.unitEnterpriseDominant.path) : [];
  BaiduMapBound.value = res.unitEnterpriseDominant.bound ? res.unitEnterpriseDominant.bound : [];
  DominantType.value=res.unitEnterpriseDominant.dominantType
  record.value = (res.unitEnterpriseDominant || {}) as UnitEnterpriseDominant;
  record.value.__t = new Date().getTime();
  const unionEnterpriseId = record.value.unionEnterprise;
  if (unionEnterpriseId) {
      const officeData = await officeTreeData();
      const findOffice = findItemById(officeData, unionEnterpriseId);
      if (findOffice) {
          record.value.enterpriseName = findOffice.name;
      }
  }
  if (record.value.path) {
      try {
          path.value = JSON.parse(record.value.path);
      } catch (error) {
          console.error('解析围栏数据失败:', error);
      }
  }
  if (record.value.bound) {
      try {
          bound.value = JSON.parse(record.value.bound);
      } catch (error) {
          console.error('解析 bound 数据失败:', error);
      }
  }
  setFieldsValue(record.value);
  setDrawerProps({ loading: false });
});

const handleOverlayComplete = (newpath) => {
  path.value = newpath;
  console.log('Received fence data:', newpath);
};

const handleClearPath = () => {
  path.value = [];
  BaiduMapPath.value = [];
  console.log('Fence data cleared:', path.value);
};

const handleMapClick = (BaiduBound) => {
  if (Array.isArray(BaiduBound) && BaiduBound.length === 1) {
      bound.value = BaiduBound;
      console.log('Received BaiduBound:', bound.value);
  } else {
      console.error('传入的 BaiduBound 数据格式不符合要求:', BaiduBound);
  }
};
const handleAddressReceived = async (address) => {
  console.log('Received address:', address);
  const currentFormData = await getFieldsValue();
  const newFormData = { ...currentFormData, address };
  setFieldsValue(newFormData);
};

function findItemById(data, id) {
  for (let i = 0; i < data.length; i++) {
      if (data[i].id === id) {
          return data[i];
      }
      if (data[i].children && data[i].children.length > 0) {
          const result = findItemById(data[i].children, id);
          if (result) {
              return result;
          }
      }
  }
  return null;
}
let isSubmitSuccess = false; // 新增标志位，用于记录提交是否成功
const handleSubmit = async () => {
  try {
      let data = await validate();
      data = {
          ...data,
          path: JSON.stringify(path.value),
          bound: JSON.stringify(bound.value),
          unitCode: data.unitCode,
          enterpriseName: data.enterpriseName
      };
      setDrawerProps({ confirmLoading: true });
      const params: any = {
          isNewRecord: record.value.isNewRecord,
          tid: record.value.tid
      };
      console.log('data', data);
      const res = await unitEnterpriseDominantSave(params, data);
      showMessage(res.message);
      if (res.result === 'true') { // 检查接口返回的 result 值
          isSubmitSuccess = true;
          ShowMessage.value = res.message
          if (record.value.isNewRecord) {
              showContractDialog.value = true;
          }
      } else {
          isSubmitSuccess = false;
      }
    //   setTimeout(closeDrawer);
      emit('success', data);
  } catch (error: any) {
      if (error && error.errorFields) {
          showMessage(error.message || t('common.validateError'));
      }
      console.log('error', error);
      isSubmitSuccess = false; // 提交失败时设置标志位为 false
  } finally {
      setDrawerProps({ confirmLoading: false });
  }
};

// // 定义 handleBuildEdit 方法
// const handleBuildEdit = () => {
//   router.push({
//     path: `/unitmanage/unitBuilding/list`,
//     query: {
//       unitCode: record.value.unitCode // 传递 unitCode 参数
//     }
//   });
// };
const [registerBuildDrawer, { openDrawer: openBuildDrawer }] = useDrawer();

const handleBuildEdit=async ()=>{
    await handleSubmit();
    if (isSubmitSuccess) { // 检查提交是否成功
        await openBuildDrawer();
    } else {
        showMessage('缺少必填数据，请检查后提交');
    }
}

</script>